import { useLocation, useNavigate } from "react-router-dom"
import RouterView from "./routerView"
import { useEffect } from "react";

function BeforeRouter({routerMap}) {
    console.log(routerMap);
    const navigate=useNavigate()
    let current=null
    const findRoute=(pathname,routerMap)=>{
        for(let val of routerMap){
            if(val.path===pathname){
                current=val
                break
            }
            if(val.children && val.children.length>0){
                findRoute(pathname,val.children)
            }
        }
    }
    const userRouter=(location)=>{
        let {pathname} = location
        findRoute(pathname,routerMap)
        console.log(current);
        if(!current){
            navigate('/404')
            return
        }
        if(current.auth && current.path.indexOf('/login')===-1){
            let token=sessionStorage.getItem('token')
            if(!token){
                navigate('/login')
                return
            }
        }
    }
    let location = useLocation()
    // console.log(location);
    useEffect(()=>{
        userRouter(location)
    },[location])
    return <RouterView routerMap={routerMap}></RouterView>
}
export default BeforeRouter